package com.juntuo.controller;

import com.github.pagehelper.PageInfo;
import com.juntuo.Enums.Constants;
import com.juntuo.entity.Role;
import com.juntuo.entity.User;
import com.juntuo.service.UserService;
import com.juntuo.shiro.ShiroUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @RequestMapping("/index")
    public String toIndex(){
        return "/user/index";
    }

    @RequestMapping("/center")
    public String toCenter(){
        return "/user/center";
    }

    @RequestMapping(value="/password",method = RequestMethod.GET)
    public String toPassword(){
        return "/user/password";
    }

    @RequestMapping("/page")
    @ResponseBody
    public PageInfo<Map<String,Object>> getPage(int pageNumber, int pageSize, String username){
        return userService.findPagedUsers(pageNumber,pageSize,username);
    }

    @ResponseBody
    @RequestMapping(value="/password",method = RequestMethod.POST)
    public int chengePassword(String oldPassword,String newPassword,HttpServletRequest request){
        User user = ShiroUtil.currentUser();
        if(oldPassword.equals(user.getPassword())){
            user.setPassword(newPassword);
            userService.updateByPrimaryKeySelective(user);
            ShiroUtil.logout(request);
            return 1;
        }else{
            return 0;
        }
    }

    @RequestMapping("/save")
    @ResponseBody
    public boolean saveOne(User user){
//        if(user.getCompanyId()!=null){
//            Role role = new Role();
//            role.setType(Constants.ROLE_COMPANY);
//            role=roleService.selectOne(role);
//            user.setRoleId(role.getId());
//        }
//        if(user.getId()==null || user.getId()==0){
//            user.setCreateTime(new Date());
//            userService.insert(user);
//        }else{
//            userService.updateByPrimaryKeySelective(user);
//        }

        return true;
    }


    @RequestMapping("/delete/{id}")
    @ResponseBody
    public int deleteOne(@PathVariable int id){
        User user = new User();
        user.setId(id);
        userService.delete(user);
        return 1;
    }
}
